package com.eiisan.user.service.impl;

import com.eiisan.core.util.api.Result;
import com.eiisan.user.mapper.UserMapper;
import com.eiisan.user.model.domain.User;
import com.eiisan.user.model.dto.UserRegisterDto;
import com.eiisan.user.service.UserService;
import com.eiisan.weixin.web.feign.WeiXinVerifyCodeFeignApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: UserServiceImpl
 * @Author gragonfly
 * @Date 2019/6/25
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeiXinVerifyCodeFeignApi weiXinFeignApi;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Result<Boolean> register(UserRegisterDto param, String weixinCode) {
        if (StringUtils.isEmpty(param.getPassword())) {
            return Result.errorRequest("密码不能为空");
        }
        if (StringUtils.isEmpty(param.getEmail())) {
            return Result.errorRequest("邮箱不能为空");
        }
        if (StringUtils.isEmpty(param.getMobile())) {
            return Result.errorRequest("手机号不能为空");
        }
        if (StringUtils.isEmpty(weixinCode)) {
            return Result.errorRequest("微信验证码不能为空");
        }
        Result<Boolean> booleanResult = null;
        try {
            booleanResult = weiXinFeignApi.checkWeiXinVerifyCode(param.getMobile(), weixinCode);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error(e.getMessage());
            return Result.errorServe();
        }
        if(booleanResult == null){
            return Result.errorServe();
        }
        if(!booleanResult.getData()){
            return Result.errorRequest("微信验证码不正确");
        }
        User user = new User();
        user.setCreateTime(new Date());
        user.setUserName(param.getUserName());
        user.setPassword(param.getPassword());
        user.setNickName(param.getNickName());
        user.setEmail(param.getEmail());
        user.setMobile(param.getMobile());
        user.setSex(param.getSex());
        user.setUserStatus((byte) 1);

        //暂时写死 角色id 默认为1
        user.setRoleId(1L);
        userMapper.register(user);
        return Result.success();
    }

    @Override
    public List<User> finAllTest() {
        return userMapper.finAllTest();
    }

    @Override
    public Result<Boolean> checkMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return Result.errorRequest("手机号不能为空");
        }
        User user = userMapper.getUserByMobile(mobile);
        return Result.success(user != null);
    }
}
